/*
 * @Author: wangqizhang
 * @Date: 2024-04-25 13:59:29
 * @LastEditors: wangqizhang
 * @LastEditTime: 2024-05-24 18:58:22
 * @FilePath: /suixinji-react/src/page/note/index.tsx
 * @Description:
 *
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
 */
import { useState, useEffect } from 'react';
import { Card, Space, Typography, message } from 'antd';
import { EditOutlined, SaveOutlined } from '@ant-design/icons';
import { NoteProps } from '../../type';
import { useLocation } from 'react-router-dom';
import NotePreview from '../../components/NotePreview';
import { updateNote } from '../../api';
import SuperMd from '../../components/SuperMd';
import SuperRich from '../../components/SuperRich';

const Note = (params: NoteProps) => {
  const location = useLocation();
  const [state, setState] = useState<any>({});
  const [isPreview, setIsPreview] = useState(true);

  useEffect(() => {
    const noteInfo = JSON.parse(location.state);
    noteInfo.note_content = noteInfo.note_content ?? '';
    setState(noteInfo);
  }, [location]);
  const changStatus = () => {
    setIsPreview(!isPreview);
  };
  const richTextChange = (value: string) => {
    setState({ ...state, note_content: value });
  };
  const markdownChange = (value: string) => {
    setState({ ...state, note_content: value });
  };
  const saveNote = async () => {
    const res = await updateNote({ ...state });
    if (res.code === '0000') {
      message.success('保存成功');
      setIsPreview(true);
    } else {
      message.error('保存失败');
    }
  };
  const { Title, Paragraph, Text, Link } = Typography;
  return (
    <Card
      title={state.note_title}
      extra={
        <Space>
          <a onClick={changStatus}>
            <EditOutlined></EditOutlined>编辑
          </a>
          <a onClick={saveNote}>
            <SaveOutlined></SaveOutlined>保存
          </a>
        </Space>
      }
    >
      <Paragraph>
        <Title level={3}>描述：</Title>
        {state.note_description}
      </Paragraph>
      {isPreview ? (
        <NotePreview
          type={state.note_type}
          value={state.note_content}
        ></NotePreview>
      ) : (
        <div>
          {state.note_type === 'markdown' ? (
            <SuperMd
              value={state.note_content}
              onChange={markdownChange}
            ></SuperMd>
          ) : (
            <SuperRich
              onChange={richTextChange}
              value={state.note_content}
            ></SuperRich>
          )}
        </div>
      )}
    </Card>
  );
};
export default Note;
